//
//  MCReportFormsViewController.swift
//  StoreManage
//
//  Created by MC on 2018/8/10.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

class MCReportFormsViewController: MCViewController {

    public var isDay = true  // 日/月统计
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        managerClosure()
        
        //TODO: todo
        // 控制时间
        sendNetworking(timeStr: getCurrentTime())
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Closure
    func managerClosure() { }
    
    // MARK: - Action
    @objc func timeLeftButtonClicked() {
        let currentTime = timeView.showLabel.text ?? ""
        
        sendNetworking(timeStr: getBeforeOrAfterTime(timeStr: currentTime, isBefore: true).0)
    }
    
    @objc func timeRightButtonClicked() {
        let currentTime = timeView.showLabel.text ?? ""
        
        let tuples = getBeforeOrAfterTime(timeStr: currentTime, isBefore: false)
        
        if tuples.1 {
            MCHUD_text(message: "已经是最新的数据啦", view: self.view, delay: 1.2)
        } else {
            sendNetworking(timeStr: tuples.0)
        }
    }

    
    // MARK: - Network
    func sendNetworking(timeStr:String) {
        
        timeView.showLabel.text = timeStr
        
        let para = [
            "date" : timeStr,
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_getOrderStatisticsChart, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            let dataDict = response["data"] as? [String : AnyObject] ?? [:]
            
            let yesTotalPrice = dataDict["yesTotalPrice"] as? NSNumber ?? 0
            let yesIncPrice = dataDict["yesIncPrice"] as? NSNumber ?? 0
            let totalPrice = dataDict["totalPrice"] as? NSNumber ?? 0
           
            let yesOrderCount = dataDict["yesOrderCount"] as? NSNumber ?? 0
            let yesIncOrder = dataDict["yesIncOrder"] as? NSNumber ?? 0
            let orderCount = dataDict["orderCount"] as? NSNumber ?? 0

            self.salesView.leftView.bottomLabel.text = MCString_judgemantDecimalsIsZero(figure: yesTotalPrice.intValue)
            self.salesView.centerView.bottomLabel.text = MCString_judgemantDecimalsIsZero(figure: yesIncPrice.intValue)
            self.salesView.rightView.bottomLabel.text = MCString_judgemantDecimalsIsZero(figure: totalPrice.intValue)

            self.orderView.leftView.bottomLabel.text = yesOrderCount.stringValue
            self.orderView.centerView.bottomLabel.text = yesIncOrder.stringValue
            self.orderView.rightView.bottomLabel.text = orderCount.stringValue
            
            
            // 获取图标的数据
            let chartList = dataDict["chartList"] as? NSArray ?? []
            
            self.timeArrayM.removeAllObjects()
            self.salesDataArrayM.removeAllObjects()
            self.orderDataArrayM.removeAllObjects()

            for dict in chartList {
                let dictTemp = dict as? [String:Any] ?? [:]
                let createTime = dictTemp["createTime"] as? String ?? ""
                let orderCount = dictTemp["orderCount"] as? NSNumber ?? 0
                let totalPrice = dictTemp["totalPrice"] as? NSNumber ?? 0
                self.timeArrayM.add(self.editTime(timeStr: createTime))
                self.salesDataArrayM.add(totalPrice.doubleValue/100.0)
                self.orderDataArrayM.add(orderCount.doubleValue)
            }
          
            self.salesView.dataTuples = (self.timeArrayM as! [String],self.salesDataArrayM as! [Double])
            self.orderView.dataTuples = (self.timeArrayM as! [String],self.orderDataArrayM as! [Double])

            
        }, dislike: { (response) in }) { (error) in }
    }
    
    // MARK: - Method
    func baseSetting() { }
    
    // 转换时间的显示
    func editTime(timeStr:String) -> String {
        if isDay {  // 日统计，“08-08”
            return timeStr.MCString_suffix(index: 5)
        } else {  // 月统计  “8月”
            return timeStr.MCString_suffix(index: 2) + "月"
        }
    }
    
    // 获取当前时间，更加type判断是年月，还是年月日
    func getCurrentTime() -> String {
        let date = Date.init()
        let formatter = DateFormatter.init()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//        let locale = Locale.init(identifier: "zh_CN")
//        formatter.locale = locale
        
        formatter.timeZone = TimeZone.init(identifier: "Asia/Shanghai")
        
        var timeStr = formatter.string(from: date)
        
        
        if isDay {
           timeStr = timeStr.MCString_prefix(index: 10)
        } else {
            timeStr = timeStr.MCString_prefix(index: 7)
        }
        
        return timeStr
    }
    // 获取上/下一天/月的时间
    func getBeforeOrAfterTime(timeStr:String,isBefore:Bool) -> (String,Bool) {
        

        let wantTimeStr = getWantDate(dateStr: timeStr, isDay: isDay, isBefore: isBefore)
        
        
        let b = isToday(dateStr: wantTimeStr, isBefore: isBefore)
        
        return (wantTimeStr,b)
        

        
    }
    
    /**
     获取指定时间上/下一个天/月的时间
     */
    
    func getWantDate(dateStr:String,isDay:Bool,isBefore:Bool) -> String {
        
        // 将时间字符串转为date
        // 用日历获取上月/天的时间
        // 将时间转为字符串
        // 判断如果是是今天，则不让点击下一个
        

        
        let formatter = DateFormatter.init()
        
        if isDay {
            formatter.dateFormat = "yyyy-MM-dd"
        } else {
            formatter.dateFormat = "yyyy-MM"
        }
        
        formatter.timeZone = TimeZone.init(identifier: "Asia/Shanghai")

        let locale = Locale.init(identifier: "zh_CN")
        formatter.locale = locale
        let date = formatter.date(from: dateStr)
        
        let calendar = Calendar.current
        
        let unit:Set<Calendar.Component> = [.year,.month,.day]

        var com = calendar.dateComponents(unit, from: date!)
        
        if isDay {   // 天
            if isBefore {
                com.day! -= 1
            } else {
                com.day! += 1
            }
        } else {    // 月
            if isBefore {
                com.month! -= 1
            } else {
                com.month! += 1
            }
        }
        
        let wantDate = calendar.date(from: com)!
        
        
        var timeStr = formatter.string(from: wantDate)
        
        if isDay {
            timeStr = timeStr.MCString_prefix(index: 10)
        } else {
            timeStr = timeStr.MCString_prefix(index: 7)
        }
        

        
        return timeStr
        
    }
    
    func isToday(dateStr:String,isBefore:Bool)->Bool {
        /// 获取当前的时间
        
        
        
        let nowStr = getWantDate(dateStr: getCurrentTime(), isDay: isDay, isBefore: isBefore)
        
        
        print("\(dateStr)-----\(nowStr)")

        
        return dateStr == nowStr
    }
    
    
    func initUI() {
        view.addSubview(bgScrollView)
        bgScrollView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view)
        }
        
        bgScrollView.addSubview(timeView)
        timeView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(view)
            make.width.equalTo(MCScreenWidth)
            make.top.equalTo(20)
            make.height.equalTo(30)
        }
        
        bgScrollView.addSubview(salesView)
        salesView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(bgScrollView)
            make.width.equalTo(MCScreenWidth)
            make.height.equalTo(313)
            make.top.equalTo(timeView.snp.bottom).offset(20)
        }
        
        bgScrollView.addSubview(orderView)
        orderView.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(bgScrollView)
            make.width.equalTo(MCScreenWidth)
            make.height.equalTo(313)
            make.top.equalTo(salesView.snp.bottom).offset(0)
        }
        


        bgScrollView.contentSize = CGSize.init(width: MCScreenWidth, height: 313*2 + 30 + 35)
    }
    
    // MARK: - Setter & Getter
    lazy var bgScrollView: UIScrollView = {
        let s = UIScrollView()
        return s
    }()
    
    lazy var timeView: MCReportFormsTimeView = {
        let view = MCReportFormsTimeView()
        view.leftButton.addTarget(self, action: #selector(timeLeftButtonClicked), for: .touchUpInside)
        view.rightButton.addTarget(self, action: #selector(timeRightButtonClicked), for: .touchUpInside)

        return view
    }()
    
    lazy var salesView: MCReportFormsItemView = {
        let view = MCReportFormsItemView()
        view.promptLabel.text = "销售额"
        view.leftView.topLabel.text = "昨日销售额"
        view.centerView.topLabel.text = "昨日净增销售额"
        view.rightView.topLabel.text = "本月销售额"

        return view
    }()
    
    lazy var orderView: MCReportFormsItemView = {
        let view = MCReportFormsItemView()
        view.promptLabel.text = "订单量"
        view.leftView.topLabel.text =  "昨日订单额量"
        view.centerView.topLabel.text = "昨日净增订单量"
        view.rightView.topLabel.text = "本月订单量"
        return view
    }()
    
    
    lazy var timeArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var salesDataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var orderDataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
}



class MCReportFormsTimeView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(leftButton)
        leftButton.snp.remakeConstraints { (make) ->Void in
            make.left.equalTo(0)
            make.centerY.equalTo(self)
            make.size.equalTo(CGSize.init(width: 30, height: 30))
        }
        
        self.addSubview(rightButton)
        rightButton.snp.remakeConstraints { (make) ->Void in
            make.right.equalTo(0)
            make.centerY.equalTo(self)
            make.size.equalTo(CGSize.init(width: 30, height: 30))
        }
        
        self.addSubview(showLabel)
        showLabel.snp.remakeConstraints { (make) ->Void in
            make.centerY.equalTo(self)
            make.right.equalTo(rightButton.snp.left).offset(-10)
            make.left.equalTo(leftButton.snp.right).offset(10)
            make.height.equalTo(30)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    lazy var showLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor.MCGray_light
        label.textAlignment = NSTextAlignment.center
        label.textColor = UIColor.MCWords
        label.text = "2018-07-11"
        label.font = MCFont(14)
        return label
    }()
    
    lazy var leftButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.setImage(#imageLiteral(resourceName: "Bill_left"), for: .normal)
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.right
        return button
    }()
    
    lazy var rightButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.setImage(#imageLiteral(resourceName: "Bill_right"), for: .normal)
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left
        return button
    }()
}
